package com.tg.app.activity.device;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.core.util.Consumer;

import com.appbase.custom.constant.DeviceStateConstants;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.tange.base.toolkit.DateUtil;
import com.tange.base.toolkit.DimenUtil;
import com.tange.base.toolkit.StringUtils;
import com.tange.base.toolkit.TGThreadPool;
import com.tange.core.data.structure.Ret;
import com.tange.core.device.facade.ConnectStatus;
import com.tange.core.device.facade.Status;
import com.tange.core.device.talk.DeviceTalkback;
import com.tange.core.media.render.AudioMode;
import com.tange.core.media.render.DeviceMediaRender;
import com.tange.core.media.render.DeviceScreenRecord;
import com.tange.core.media.source.impl.live.LiveResolutions;
import com.tange.core.media.source.impl.live.PiPDeviceLiveMediaSource;
import com.tange.core.universal.instructions.PtzInstruction;
import com.tg.app.R;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.camera.CameraHelper;
import com.tg.app.helper.ActivityHelper;
import com.tg.app.helper.AppHelper;
import com.tg.app.helper.CameraBottomSheetDialogHelper;
import com.tg.app.helper.DeviceFeatureHelper;
import com.tg.app.helper.DeviceHelper;
import com.tg.app.helper.MultiPlayerHelper;
import com.tg.app.util.LocalThumbnailUtils;
import com.tg.app.view.MsgCenterToast;
import com.tg.app.view.QualityUIHelper;
import com.tg.app.widget.BottomSheetListDialog;
import com.tg.app.widget.PtzControlView;
import com.tg.app.widget.ZoomView;
import com.tg.appcommon.android.ImageUtils;
import com.tg.appcommon.android.Packet;
import com.tg.appcommon.android.PermissionUtil;
import com.tg.appcommon.android.ResourcesUtil;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


public class CameraPipLiveActivity extends LiveActivity {
    private FrameLayout playerContainerPiP;
    private int resolutionIndex = AVIOCTRLDEFs.AVIOCTRL_QUALITY_MIN;
    private int resolutionPipIndex = AVIOCTRLDEFs.AVIOCTRL_QUALITY_MIN;
    private DeviceMediaRender deviceMediaRenderPiP;
    private PtzInstruction ptzInstruction;

    private final Handler mHandler = new Handler(message -> {
        switch (message.what) {
            case EVENT_SEND_PTZCMD_LONG:
            case EVENT_SEND_FOCUSCMD_LONG:
                if (message.what == EVENT_SEND_PTZCMD_LONG){
                    ptzControlView.setSendPTZCmd(true);
                }
                if (deviceFacade != null) {
                    TGLog.d(TAG, "currentPlayer " + currentPlayer);
                    AppHelper.sendPTZCMD(deviceFacade, message.arg1, currentPlayer);
                }
                break;
        }
        return false;
    });

    @Override
    public void updateLayout(boolean update) {
        selectedLayout();
        showBanner();
        setTalkbackMode();
    }

    @Override
    public void createDeviceMediaRender() {
        deviceMediaSource = new PiPDeviceLiveMediaSource(deviceFacade);
        deviceMediaRender = new DeviceMediaRender(this, deviceMediaSource);
        deviceMediaRenderPiP = new DeviceMediaRender(this, deviceMediaSource);
        ptzInstruction = new PtzInstruction(deviceFacade);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pip_device_live);
        hideActionBar();
        if (DeviceHelper.is4GDevice(mDevice) && !DeviceHelper.is4GExpired(mDevice, true)) {
            if (mDevice.isOnline()) {
                deviceFacade.connect();
            }
        }
        initView();
        initData();
    }

    private void switchPtzControl(){
        ptzContainer.setVisibility(View.VISIBLE);
        xBanner.setVisibility(View.GONE);
    }

    private void switchFullScreen() {
        setRequestedOrientation(isLandscape? ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED : ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        findViewById(R.id.setting).setVisibility(isLandscape? View.VISIBLE : View.GONE);
        xBanner.setVisibility(isLandscape? View.VISIBLE : View.GONE);
        ptzContainer.setVisibility(View.GONE);
        isLandscape = !isLandscape;
        if (isLandscape) {
            playerContainer.setVisibility(currentPlayer == 0? View.VISIBLE : View.GONE);
            playerContainerPiP.setVisibility(currentPlayer == 0? View.GONE : View.VISIBLE);
            playerContainer.setBackgroundColor(Color.TRANSPARENT);
            playerContainer.setPadding(0, 0, 0, 0);
            playerContainerPiP.setBackgroundColor(Color.TRANSPARENT);
            playerContainerPiP.setPadding(0, 0, 0, 0);
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
            layoutParams.gravity = Gravity.CENTER;

            if (currentPlayer == 0){
                deviceMediaRender.detach();
                deviceMediaRender.attach(playerContainer, layoutParams);
                playerContainer.post(() -> deviceMediaRender.resize());
            }else{
                deviceMediaRenderPiP.detach();
                deviceMediaRenderPiP.attach(playerContainerPiP, layoutParams);
                playerContainerPiP.post(() -> deviceMediaRenderPiP.resize());
            }
        } else {
            playerContainer.setVisibility(View.VISIBLE);
            playerContainerPiP.setVisibility(View.VISIBLE);
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
            layoutParams.gravity = Gravity.BOTTOM;
            deviceMediaRender.detach();
            deviceMediaRender.attach(playerContainer, layoutParams);

            FrameLayout.LayoutParams layoutParams1 = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
            layoutParams1.gravity = Gravity.TOP;
            deviceMediaRenderPiP.detach();
            deviceMediaRenderPiP.attach(playerContainerPiP, layoutParams1);

            playerContainer.post(() -> deviceMediaRender.resize());
            playerContainerPiP.post(() -> deviceMediaRenderPiP.resize());
            selectedLayout();
        }
    }

    public void screenSaveLocal() {
        Bitmap bmp = currentPlayer == 0? deviceMediaRender.screenshot() : deviceMediaRenderPiP.screenshot();
        if (bmp == null) {
            return;
        }
        if (mDevice != null) {
            int pixel = bmp.getPixel(0,0);
            int pixel20 = bmp.getPixel(20,20);
            if (pixel==pixel20&&pixel==0){
                return;
            }
            LocalThumbnailUtils.getInstance().saveLocalThumbnail(bmp, mDevice.uuid);
        }
    }

    public void saveBmp2Gallery() {
        Bitmap bmp = currentPlayer == 0? deviceMediaRender.screenshot() : deviceMediaRenderPiP.screenshot();
        if (bmp == null) {
            return;
        }
        int ret = ImageUtils.saveFile(CameraPipLiveActivity.this, bmp);
        if (ret == 0) {
            showToast(R.string.picture_saved_successfully);
        } else {
            showToast(R.string.picture_saved_failed);
        }
    }

    public void screenCapClick() {
        String title = getString(com.module.appcommon.R.string.no_permission_to_work_with_screenvideo);
        String content = getString(com.module.appcommon.R.string.enable_permission_storage);
        PermissionUtil permissionUtil = new PermissionUtil(this);
        permissionUtil.checkPermissionFirst(Permission.WRITE_EXTERNAL_STORAGE, this::recordStart, title, content);
    }

    public void screenSaveEnd() {
        TGLog.d(TAG, "click screenSaveEnd");
        recordTimeLayout.setVisibility(View.GONE);
    }

    public void recordingUpdate(long duration) {
        int time = (int) (duration / 1000);
        String timeStr = DateUtil.formatTimeHHmmss(time);
        timeStr = timeStr.substring(3);
        recordTimeText.setText(timeStr);
        if (recordTimeLayout.getVisibility() == View.GONE) {
            TGLog.d(TAG, "click recordingUpdate");
            TGLog.trace(TAG);
            recordTimeLayout.setVisibility(View.VISIBLE);
        }
    }

    private void recordStart() {
        if (currentPlayer == 0){
            if (!deviceMediaRender.screenRecord().isStarted()) {
                deviceMediaRender.screenRecord().start();
                TGToast.showToast(R.string.start_screen_record);
            }
        }else{
            if (!deviceMediaRenderPiP.screenRecord().isStarted()) {
                deviceMediaRenderPiP.screenRecord().start();
                TGToast.showToast(R.string.start_screen_record);
            }
        }
    }


    public void screenShotResult() {
        String title =  getString(com.module.appcommon.R.string.no_permission_to_work_with_screenvideo);
        String content =  getString(com.module.appcommon.R.string.enable_permission_storage);
        PermissionUtil permissionUtil = new PermissionUtil(CameraPipLiveActivity.this);
        permissionUtil.checkPermissionFirst(Permission.WRITE_EXTERNAL_STORAGE, this::saveBmp2Gallery, title, content);
    }

    private void requestAudioPermission() {
        XXPermissions.with(this).permission(Permission.RECORD_AUDIO).request(new OnPermissionCallback() {
            @Override
            public void onGranted(List<String> permissions, boolean all) {
                //权限被允许
                hasAudioPermission = true;
            }

            @Override
            public void onDenied(List<String> permissions, boolean never) {
                hasAudioPermission = false;
                TGToast.showToast(R.string.audio_permission_deny);
            }
        });

    }

    private void createDeviceTalkback(){
        if (deviceTalkback == null) {
            deviceTalkback = new DeviceTalkback(deviceFacade);
            deviceTalkback.observeStatus(ret -> {
                if (!ret.getSuccess()) {
                    deviceFunHelper.setIntercomImageResource(R.drawable.ic_tange_live_mic);
                }
            });
        }
    }

    private void setTalkbackMode(){
        if (DeviceFeatureHelper.supportSpeaker(mDeviceFeature)) {
            createDeviceTalkback();
            if (DeviceFeatureHelper.isAec(mDeviceFeature)){
                deviceTalkback.setMode(AudioMode.MODE_IN_COMMUNICATION);
            }else{
                deviceTalkback.setMode(AudioMode.MODE_NORMAL);
            }
        }
    }

    private void talkback(final ImageView imageView) {
        if (!deviceFacade.connected()) {
            TGToast.showToast(R.string.talk_finish_record);
            return;
        }

        requestAudioPermission();
        if (hasAudioPermission){
            createDeviceTalkback();

            if (deviceTalkback.getStarted()) {
                deviceTalkback.stop();
                soundByStopTalkback(imageView);
            } else {
                deviceTalkback.start();
                soundByStartTalkback(imageView);
            }
        }
    }

    private boolean openSound = false;

    private void soundByStartTalkback(final ImageView imageView){
        boolean isAec = DeviceFeatureHelper.isAec(mDeviceFeature);
        imageView.setImageResource(R.drawable.ic_tange_live_mic_on);
        deviceFunHelper.setIntercomImageResource(R.drawable.ic_tange_live_mic_on);
        TGLog.d(TAG, "isAec = " + isAec);
        if (!isAec) {
            openSound = deviceMediaSource.isAudioProduceEnabled();
            if (openSound){
                switchAudio(null);
            }
        }
    }

    private void soundByStopTalkback(final ImageView imageView){
        imageView.setImageResource(R.drawable.ic_tange_live_mic);
        boolean isAec = DeviceFeatureHelper.isAec(mDeviceFeature);
        deviceFunHelper.setIntercomImageResource(R.drawable.ic_tange_live_mic);
        TGLog.d(TAG, "isAec = " + isAec);
        if (!isAec) {
            if (openSound){
                switchAudio(null);
            }
        }
    }

    private boolean canClickDeviceFun(){
        if (connectView.getVisibility() == View.VISIBLE){
            String text = connectView.getText().toString();
            if (StringUtils.equalsIgnoreCase(text, getString(R.string.deivce_add_network_error))){
                return false;
            }

            if (StringUtils.equalsIgnoreCase(text, getString(R.string.sim_service_expired))){
                return false;
            }

            if (StringUtils.equalsIgnoreCase(text, getString(R.string.camera_offline))){
                return false;
            }
        }

        if (loadingView.getVisibility() == View.VISIBLE){
            return false;
        }

        return true;
    }


    private void showBanner(){
        List<String> list = new ArrayList<>();
        if (DeviceFeatureHelper.supportPTZ(mDeviceFeature, currentPlayer)) {
            list.add(ResourcesUtil.getString(R.string.txt_switch));
        }else if (ptzContainer != null){
            ptzContainer.setVisibility(View.GONE);
        }

        list.add(ResourcesUtil.getString(R.string.fullscreen));
        if (DeviceFeatureHelper.supportSpeaker(mDeviceFeature)){
            list.add(ResourcesUtil.getString(R.string.click_to_talk));
        }

        list.add(ResourcesUtil.getString(R.string.clarity));
        list.add(ResourcesUtil.getString(R.string.event_sound));
        list.add(ResourcesUtil.getString(R.string.record_screen));
        list.add(ResourcesUtil.getString(R.string.screen_shot));

        setResolution();
        deviceFunHelper.setParam(list);
        TGThreadPool.executeOnUiThread(() -> {
            deviceFunHelper.refreshTools();
            deviceFunHelper.initBanner(CameraPipLiveActivity.this);
            deviceFunHelper.showBanner(true);
        });
    }

    private void setFunListener(){
        deviceFunHelper.setListener((view, title) -> {
            if (canClickDeviceFun()){
                TGLog.i(TAG, "onBannerClick: " + title);
                if (!StringUtils.isEmpty(title)){
                    if (StringUtils.equalsIgnoreCase(title, ResourcesUtil.getString(R.string.fullscreen))) {
                        switchFullScreen();
                    }else if (StringUtils.equalsIgnoreCase(title, ResourcesUtil.getString(R.string.click_to_talk))) {
                        if (view instanceof ImageView) {
                            talkback((ImageView) view);
                        }
                    }else if (StringUtils.equalsIgnoreCase(title, ResourcesUtil.getString(R.string.clarity))) {
                        queryResolutions(true);
                    }else if (StringUtils.equalsIgnoreCase(title, ResourcesUtil.getString(R.string.event_sound))) {
                        if (view instanceof ImageView) {
                            switchAudio((ImageView) view);
                        }
                    }else if (StringUtils.equalsIgnoreCase(title, ResourcesUtil.getString(R.string.record_screen))) {
                        screenCapClick();
                    }else if (StringUtils.equalsIgnoreCase(title, ResourcesUtil.getString(R.string.screen_shot))) {
                        screenShotResult();
                    }else if (StringUtils.equalsIgnoreCase(title, ResourcesUtil.getString(R.string.txt_switch))){
                        switchPtzControl();
                    }
                }
            }else{
                showErrorTip();
            }

        });
    }

    private void initData(){
        setFunListener();
        deviceMediaRender.setVideoFrameFilter(mediaFrame -> mediaFrame != null && mediaFrame.getData().getSubType() == 0);
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        layoutParams.gravity = Gravity.BOTTOM;
        deviceMediaRender.attach(playerContainer, layoutParams);
        deviceMediaRender.observeFirstFrameRendered(() -> {
            TGLog.i(TAG, "[first-rendered] ");
            rendered = true;
            loadingView.setVisibility(View.GONE);
            selectedLayout();
        });

        deviceMediaRender.screenRecord().setRecordStatusObserver(new DeviceScreenRecord.RecordStatusObserver() {
            @Override
            public void onStart() {
                TGLog.i(TAG, "[RecordStatusObserver][onStart] ");
                isSaving = true;
                recordingUpdate(0);
            }

            @Override
            public void onDurationUpdate(long duration) {
                TGLog.i(TAG, "[RecordStatusObserver][onDurationUpdate] ");
                if (isSaving) {
                    runOnUiThread(() -> recordingUpdate(duration));
                }
            }

            @Override
            public void onComplete(boolean success) {
                TGLog.i(TAG, "[RecordStatusObserver][RecordStatusObserver] " + success);
                isSaving = false;
                runOnUiThread(() -> screenSaveEnd());
            }
        });

        deviceMediaRenderPiP.setVideoFrameFilter(mediaFrame -> mediaFrame != null && mediaFrame.getData().getSubType() == 1);
        FrameLayout.LayoutParams layoutParams1 = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        layoutParams1.gravity = Gravity.TOP;
        deviceMediaRenderPiP.attach(playerContainerPiP, layoutParams1);
        deviceMediaRenderPiP.observeFirstFrameRendered(() -> {
            TGLog.i(TAG, "[first-rendered] ");
            rendered = true;
            loadingView.setVisibility(View.GONE);
            selectedLayout();
        });


        deviceMediaRenderPiP.screenRecord().setRecordStatusObserver(new DeviceScreenRecord.RecordStatusObserver() {
            @Override
            public void onStart() {
                TGLog.i(TAG, "[RecordStatusObserver][onStart] ");
                isSaving = true;
                recordingUpdate(0);
            }

            @Override
            public void onDurationUpdate(long duration) {
                TGLog.i(TAG, "[RecordStatusObserver][onDurationUpdate] ");
                if (isSaving) {
                    runOnUiThread(() -> recordingUpdate(duration));
                }
            }

            @Override
            public void onComplete(boolean success) {
                TGLog.i(TAG, "[RecordStatusObserver][RecordStatusObserver] " + success);
                isSaving = false;
                runOnUiThread(() -> screenSaveEnd());
            }
        });


        setResolution();
        setTalkbackMode();
    }

    private void switchAudio(ImageView audio) {
        if (deviceMediaSource.isAudioProduceEnabled()) {

            if (audio != null) {
                audio.setImageResource(R.drawable.ic_tange_live_soundoff);
            }
            deviceFunHelper.setAudioImageResource(R.drawable.ic_tange_live_soundoff, audio == null);

            deviceMediaSource.enableAudioProduce(false);
            deviceMediaRender.enableAudioRender(false);
            deviceMediaRenderPiP.enableAudioRender(false);
        } else {
            if (audio != null) {
                audio.setImageResource(R.drawable.ic_tange_live_soundon);
            }
            deviceFunHelper.setAudioImageResource(R.drawable.ic_tange_live_soundon, audio == null);
            deviceMediaSource.enableAudioProduce(true);
            deviceMediaRender.enableAudioRender(true);
            deviceMediaRenderPiP.enableAudioRender(true);
        }
    }


    @Override
    protected void initView() {
        super.initView();
        xBanner = findViewById(R.id.banner);
        deviceFunHelper.setBanner(xBanner);
        playerContainer = findViewById(R.id.player_container);
        playerContainerPiP = findViewById(R.id.player_container_pip);
        loadingView = findViewById(R.id.loading);
        loadingView.setVisibility(View.VISIBLE);
        connectView = findViewById(R.id.connect);
        connectView.setOnClickListener(v -> {
            if (StringUtils.equalsIgnoreCase(connectView.getText().toString(), getString(R.string.deivce_add_network_error))){
                return;
            }

            if (StringUtils.equalsIgnoreCase(connectView.getText().toString(), getString(R.string.sim_service_expired))){
                return;
            }

            if (StringUtils.equalsIgnoreCase(connectView.getText().toString(), getString(R.string.camera_offline))){
                return;
            }


            connectView.setVisibility(View.GONE);
            deviceFacade.connect();
        });
        recordTimeLayout = findViewById(R.id.ll_camera_player_record_time);
        recordTimeText = findViewById(R.id.tv_camera_player_record_time);
        ptzControlView = findViewById(R.id.ptz_horizontal_control);
        findViewById(R.id.back).setOnClickListener(v -> {
            if (isLandscape) {
                switchFullScreen();
            } else {
                finish();
            }
        });
        findViewById(R.id.setting).setOnClickListener(v -> jumpSettings());
        recordTimeLayout.setOnClickListener(v -> {
            String name = "TG-" + System.currentTimeMillis() + ".mp4";
            File file = new File(albumPath, name);
            if (currentPlayer == 0){
                deviceMediaRender.screenRecord().finish(file.getAbsolutePath(), success -> {
                    if (success) {
                        showToast(getString(R.string.record_save));
                    }
                });
            }else{
                deviceMediaRenderPiP.screenRecord().finish(file.getAbsolutePath(), success -> {
                    if (success) {
                        showToast(getString(R.string.record_save));
                    }
                });
            }

        });
        showBanner();
        ptzContainer = findViewById(R.id.ptz_container);
        ptzControlView.setClickable(true);
        ptzControlView.setOnPtzControlTouchListener(mOnPtzControlTouchListener);
        findViewById(R.id.btn_dialog_ptz_control_close).setOnClickListener(v -> {
            xBanner.setVisibility(View.VISIBLE);
            ptzContainer.setVisibility(View.GONE);
        });
        selectedLayout();

        playerContainer.setOnClickListener(v -> switchPlayer(PLAYER_ID_MAIN, true));
        playerContainerPiP.setOnClickListener(v -> switchPlayer(PLAYER_ID_MINI, true));
    }

    protected void jumpSettings() {
        if (deviceFacade != null) {
            unregisterICameraListener();
            ActivityHelper.jump2SettingActivityForResult(CameraPipLiveActivity.this, mDevice, mOrigin);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (mDevice != null && mDevice.isOnline()) {
            if (DeviceHelper.is4GDevice(mDevice) && DeviceHelper.is4GExpired(mDevice, true)) {
                updateServiceState();
            }else{
                deviceMediaSource.enableVideoProduce(true);
                deviceMediaRender.enableVideoRender(true);
                deviceMediaRenderPiP.enableVideoRender(true);

                deviceMediaSource.enableAudioProduce(audioEnabled);
                deviceMediaRender.enableAudioRender(audioEnabled);
                deviceMediaRenderPiP.enableAudioRender(audioEnabled);

                if (mDeviceFeature != null){
                    currentPlayer = mDeviceFeature.currentPlayer;
                }
                selectedLayout();
                keepAwake();
            }


        } else {
            findViewById(R.id.player_container_out).setVisibility(View.GONE);
            loadingView.setVisibility(View.GONE);
            connectView.setText(R.string.camera_offline);
            connectView.setVisibility(View.VISIBLE);
        }

        deviceFunHelper.setAudioImageResource(audioEnabled? R.drawable.ic_tange_live_soundon : R.drawable.ic_tange_live_soundoff);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isLandscape) {
                switchFullScreen();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        super.onPause();
        screenSaveLocal();
        deviceMediaSource.enableVideoProduce(false);
        deviceMediaSource.enableAudioProduce(false);
        deviceMediaRender.enableAudioRender(false);
        deviceMediaRender.enableVideoRender(false);

        deviceMediaRenderPiP.enableAudioRender(false);
        deviceMediaRenderPiP.enableVideoRender(false);

    }


    @Override
    public void receiveIOCtrlData(final int type, final byte[] data) {
        super.receiveIOCtrlData(type, data);
        runOnUiThread(() -> {
            if (type == AVIOCTRLDEFs.TCI_CMD_GET_RUNTIME_STATE_RESP){
                if (mDeviceFeature != null){
                    mDeviceFeature.recordFun = 1;
                    putSettingsInfo();
                }
            }else if (type == AVIOCTRLDEFs.TCI_CMD_GET_MICROPHONE_RESP) {
                byte b = Packet.byteArrayToByte_Little(data, 4);
                deviceSettingsInfo.microphoneOn = b;
                TGLog.d("CameraViewActivity",  "info.b = " + b);
                isMicrophoneClose();
                putSettingsInfo();
            } else if (type == AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_GET_FEATURE_RESP) {
                if (deviceSettingsInfo != null){
                    resolutionIndex = deviceSettingsInfo.quality;
                    resolutionPipIndex = deviceSettingsInfo.quality2;
                    if (deviceMediaSource instanceof PiPDeviceLiveMediaSource){
                        ((PiPDeviceLiveMediaSource)deviceMediaSource).switchVideoResolution(resolutionIndex);
                        ((PiPDeviceLiveMediaSource)deviceMediaSource).switchPiPVideoResolution(resolutionPipIndex);
                    }

                    showBanner();
                }
            } else if (type == AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETSTREAMCTRL_RESP) {
                deviceSettingsInfo.quality = data[4];
            } else if (type == AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETRECORD_RESP) {
                deviceSettingsInfo.recordType = Packet.byteArrayToInt_Little(data, 4);
                if (data.length > 8) {
                    deviceSettingsInfo.recordStream = data[8];
                }
                TGLog.d("VideoType", "recordType2 = " + deviceSettingsInfo.recordType);
                putSettingsInfo();

            } else if (type == AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SETSTREAMCTRL_RESP) {
                deviceSettingsInfo.quality = resolutionIndex;
                deviceSettingsInfo.quality2 = resolutionPipIndex;
                putSettingsInfo();
            } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_PRIMARY_VIEW_RESP) {
                int pos = Packet.byteArrayToInt_Little(data, 4);
                deviceSettingsInfo.zoomPos = pos;
                putSettingsInfo();
                switchPlayer(pos, false);
            } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_LIGHT_RESP){
                CameraHelper.getLightData(data, mDeviceFeature);
                putSettingsInfo();
            }  else if (type == AVIOCTRLDEFs.TCI_CMD_SET_COMMAND_RESP) {
                int command = Packet.byteArrayToInt_Little(data, 0);
                int result = Packet.byteArrayToInt_Little(data, 4);

                TGLog.d(ZoomView.TAG, "command" + command + ",result:" + result);
                if (command == AVIOCTRLDEFs.TCI_CMD_GET_RUNTIME_STATE_REQ){
                    if (result == 3 || result == 4){
                        if (mDeviceFeature != null){
                            mDeviceFeature.recordFun = 0;
                            putSettingsInfo();
                        }

                    }
                } else if (command == AVIOCTRLDEFs.TCI_CMD_GET_WIFI_SIGNALLEVEL_REQ){
                    TGLog.d("len = " + data.length);
                } else if (command == AVIOCTRLDEFs.TCL_CMD_SET_CAMERA_STATUS_REQ) {
                    TGLog.d("DeviceSettingsActivity", "mDeviceUIHelper.isClickOpenDeviceBtn():" + mDeviceUIHelper.isClickOpenDeviceBtn());
                    if (result == 0 && mDeviceUIHelper.isClickOpenDeviceBtn()) {
                        mDevice.is_open = DeviceStateConstants.DEVICE_OPEN;
                        deviceSettingsInfo.deviceStatus = DeviceStateConstants.DEVICE_OPEN;

                        startLive();

                        putSettingsInfo();
                    }
                    mDeviceUIHelper.setClickOpenDeviceBtn(false);
                }else if (command == AVIOCTRLDEFs.IOTYPE_USER_IPCAM_PTZ_COMMAND){
                //    setPtzControlViewClickable(true);
                    Activity activity = TGApplicationBase.getAppLifecycleCallbacks().getCurrentActivity();
                    if (activity instanceof CameraViewActivity){
                        TGToast.showToast(R.string.txt_gimbal_calibration_succeeded);
                    }
                } else if (command == AVIOCTRLDEFs.TCI_CMD_SET_LIGHT_REQ){
                    if (DeviceHelper.isLamp(mDevice)){
                        TGToast.showToast(result == 0? R.string.device_name_changed_success : R.string.device_name_changed_failure);
                    }
                }

            }
        });
    }

    private void showConnectionFailed(){
        connectView.setText(R.string.deivce_add_network_error);
        connectView.setVisibility(View.VISIBLE);
        loadingView.setVisibility(View.GONE);
    }

    @Override
    public void accept(ConnectStatus connectStatus) {
        Status status = connectStatus.getStatus();
        TGLog.i(TAG, "[instructionConsumer] status:" + status);
        if (status == Status.SUCCESS) {
            queryResolutions(false);
            AppHelper.getPrimaryViewCmd(deviceFacade);
            keepAwake();
        }else if (status == Status.FAILED || status == Status.DISCONNECTED_BY_DEVICE){
            TGLog.i(TAG, "[instructionConsumer] status:" + status);
            TGThreadPool.executeOnUiThread(() -> {
                TGThreadPool.executeOnUiThread(this::showConnectionFailed);
            });
        }
    }

    private BottomSheetListDialog getBottomSheetDialogHelper() {
        if (bottomSheetListDialog == null) {
            bottomSheetListDialog = new BottomSheetListDialog(this);
            bottomSheetListDialog.setCanceledOnTouchOutside(true);
            bottomSheetListDialog.setCancelable(true);
        }
        return bottomSheetListDialog;
    }

    private String getLabel(){
        for (LiveResolutions resolution : resolutions) {
            if (currentPlayer == PLAYER_ID_MAIN){
                if (resolution.getValue() == resolutionIndex){
                    return resolution.getLabel();
                }
            }else{
                if (resolution.getValue() == resolutionPipIndex){
                    return resolution.getLabel();
                }
            }
        }
        return "";
    }

    private void showPlayResolutionUI(){
        String label = getLabel();
        TGThreadPool.executeOnUiThread(() -> {
            if (StringUtils.equalsIgnoreCase("HD", label)) {
               deviceFunHelper.setResolutionImageResource(R.drawable.ic_tange_live_hd);
            } else if (StringUtils.equalsIgnoreCase("FHD", label)) {
                deviceFunHelper.setResolutionImageResource(R.drawable.ic_tange_live_fhd);
            } else if (StringUtils.equals("SD", label)) {
                deviceFunHelper.setResolutionImageResource(R.drawable.ic_tange_live_sd);
            } else if (StringUtils.equals("UHD", label)) {
                deviceFunHelper.setResolutionImageResource(R.drawable.ic_tange_live_uhd);
            }
        });
    }

    private void createResolutionSheetDialogHelper(List<String> list, int index) {
        CameraBottomSheetDialogHelper.createResolutionSheetDialogHelper(getBottomSheetDialogHelper(), list, index, (action, text, position) -> {
            if (action == BottomSheetListDialog.ACTION_RESOLUTION) {
                int current = resolutions.get(position).getValue();
                if (currentPlayer == PLAYER_ID_MAIN){
                    if (current != resolutionIndex){
                        resolutionIndex = resolutions.get(position).getValue();
                        deviceSettingsInfo.quality = resolutionIndex;
                        if (deviceMediaSource instanceof PiPDeviceLiveMediaSource){
                            ((PiPDeviceLiveMediaSource)deviceMediaSource).switchVideoResolution(resolutionIndex);
                        }
                    }
                }else{
                    if (current != resolutionPipIndex){
                        resolutionPipIndex = resolutions.get(position).getValue();
                        deviceSettingsInfo.quality2 = resolutionPipIndex;
                        if (deviceMediaSource instanceof PiPDeviceLiveMediaSource){
                            ((PiPDeviceLiveMediaSource)deviceMediaSource).switchPiPVideoResolution(resolutionPipIndex);
                        }
                    }
                }

                showPlayResolutionUI();

            }
        });
    }

    public void showResolution(List<String> list) {
        createResolutionSheetDialogHelper(list, currentPlayer == PLAYER_ID_MAIN? resolutionIndex : resolutionPipIndex);
    }

    private List<String> getResolutions(){
        String current = null;
        int currentResolution = currentPlayer == PLAYER_ID_MAIN? resolutionIndex : resolutionPipIndex;
        for (int i = 0; i < resolutions.size(); i++) {
            if (resolutions.get(i).getValue() == currentResolution) {
                current = resolutions.get(i).getLabel();
                break;
            }
        }
        List<String> list = new ArrayList<>();
        if (!StringUtils.isEmpty(current)){
            list.add(current);
        }
        for (int i = 0; i < resolutions.size(); i++) {
            list.add(resolutions.get(i).getLabel());
        }
        return list;
    }

    private void queryResolutions(final boolean showResolution) {
        TGLog.i(TAG, "[queryResolutions] start");
        if (resolutions.size() == 0){
            if (deviceMediaSource instanceof PiPDeviceLiveMediaSource){
                ((PiPDeviceLiveMediaSource)deviceMediaSource).querySupportedResolutions(listResp -> {
                    TGLog.i(TAG, "[queryResolutions] " + listResp);
                    if (listResp.getSuccess()) {
                        final List<LiveResolutions> resolutionsList = listResp.getData();
                        if (resolutionsList != null && resolutionsList.size() > 0){
                            resolutions.clear();
                            resolutions.addAll(resolutionsList);
                            if (deviceSettingsInfo != null){
                                resolutionIndex = deviceSettingsInfo.quality;
                                resolutionPipIndex = deviceSettingsInfo.quality2;
                            }else {
                                int currentVideoResolution = ((PiPDeviceLiveMediaSource)deviceMediaSource).currentVideoResolution();
                                if (currentPlayer == PLAYER_ID_MAIN){
                                    resolutionIndex = currentVideoResolution;
                                }else {
                                    resolutionPipIndex = currentVideoResolution;
                                }
                            }

                            TGLog.i(TAG, "[resolutionIndex] " + resolutionIndex + " [resolutionPipIndex] " + resolutionPipIndex);
                            if (showResolution){
                                List<String> list = getResolutions();
                                showResolution(list);
                            }else{
                                showPlayResolutionUI();
                            }
                        }
                    }
                });
            }

        }else{
            if (deviceSettingsInfo != null){
                resolutionIndex = deviceSettingsInfo.quality;
                resolutionPipIndex = deviceSettingsInfo.quality2;
            }else {
                int currentVideoResolution = ((PiPDeviceLiveMediaSource)deviceMediaSource).currentVideoResolution();
                if (currentPlayer == PLAYER_ID_MAIN){
                    resolutionIndex = currentVideoResolution;
                }else {
                    resolutionPipIndex = currentVideoResolution;
                }
            }
            if (showResolution){
                List<String> list = getResolutions();
                showResolution(list);
            }else{
                showPlayResolutionUI();
            }
        }
    }


    public void setResolution() {
        resolutionIndex = deviceSettingsInfo.quality;
        resolutionPipIndex = deviceSettingsInfo.quality2;
        TGLog.d(TAG, "[setResolution] resolutionIndex:" + resolutionIndex + " resolutionPipIndex:" + resolutionPipIndex);
        int currentResolution = currentPlayer == PLAYER_ID_MAIN? resolutionIndex : resolutionPipIndex;
        if (mDeviceFeature != null) {
            int resID = QualityUIHelper.getQualityResId(mDeviceFeature, currentResolution);
            if (resID > 0) {
                deviceFunHelper.setResolutionImageResource(resID);
            }
        } else {
            if (currentResolution == AVIOCTRLDEFs.AVIOCTRL_QUALITY_MIN) {
                deviceFunHelper.setResolutionImageResource(R.drawable.ic_tange_live_sd);
            } else {
                deviceFunHelper.setResolutionImageResource(R.drawable.ic_tange_live_hd);
            }
        }
    }

    private void onPtzShortCmd(int control, boolean isScreen) {
        TGLog.d(PtzControlView.TAG, "onPtzShortCmd = " + control + "currentPlayer " + currentPlayer);
        if (deviceFacade != null && deviceFacade.connected()) {
            mHandler.removeMessages(EVENT_SEND_PTZCMD_LONG);
            AppHelper.sendPTZCMDShort(deviceFacade, control, currentPlayer);
        }

    }

    private void onPtzStopCmd() {
        if (deviceFacade != null && deviceFacade.connected()) {
            mHandler.removeMessages(EVENT_SEND_PTZCMD_LONG);
            TGLog.d(PtzControlView.TAG, "onStopCmd ptzCmd currentPlayer " + currentPlayer);

            ptzInstruction.move(PtzInstruction.Direction.STOP, currentPlayer, new Consumer<Ret>() {
                @Override
                public void accept(Ret ret) {
                    if (ret.getSuccess()) {
                        TGLog.i(TAG, "onStopCmd ptzCmd success");
                    } else {
                        TGLog.i(TAG, "onStopCmd ptzCmd failed");
                    }
                }
            });
        }
    }

    private void onPtzLongCmd(int control, boolean isScreen) {
        if (deviceFacade != null && deviceFacade.connected()) {
            Message message = mHandler.obtainMessage();
            message.what = EVENT_SEND_PTZCMD_LONG;
            message.arg1 = control;
            mHandler.sendMessageDelayed(message, 200);
        }
    }

    private final PtzControlView.OnPtzControlTouchListener mOnPtzControlTouchListener = new PtzControlView.OnPtzControlTouchListener() {
        @Override
        public void onShortCmd(int control) {
            TGLog.i(TAG, "Ptz onShortCmd false");
            onPtzShortCmd(control, false);
        }

        @Override
        public void onStopCmd() {
            TGLog.i(TAG, "Ptz onStopCmd false");
            onPtzStopCmd();
        }

        @Override
        public void onLongCmd(int control) {
            TGLog.d(PtzControlView.TAG, "Ptz onLongCmd");
            onPtzLongCmd(control, false);
        }
    };

    @Override
    protected void updateServiceState() {
        super.updateServiceState();

        if (mDevice.isOnline()){
            if (DeviceHelper.is4GDevice(mDevice) && DeviceHelper.is4GExpired(mDevice, true)) {
                deviceFacade.disconnect();
                playerContainer.setVisibility(View.GONE);
                playerContainerPiP.setVisibility(View.GONE);
                loadingView.setVisibility(View.GONE);

                connectView.setText(R.string.sim_service_expired);
                connectView.setBackgroundResource(R.color.transparent);
                buyButton.setVisibility(View.VISIBLE);

                connectView.setVisibility(View.VISIBLE);

            }else{
                playerContainer.setVisibility(View.VISIBLE);
                playerContainerPiP.setVisibility(View.VISIBLE);
                findViewById(R.id.player_container_out).setVisibility(View.VISIBLE);
                buyButton.setVisibility(View.GONE);
                connectView.setVisibility(View.GONE);
                deviceMediaSource.enableVideoProduce(true);
                deviceMediaRender.enableVideoRender(true);
                deviceMediaRenderPiP.enableVideoRender(true);

                deviceMediaSource.enableAudioProduce(audioEnabled);
                deviceMediaRender.enableAudioRender(audioEnabled);
                deviceMediaRenderPiP.enableAudioRender(audioEnabled);

                if (mDeviceFeature != null){
                    currentPlayer = mDeviceFeature.currentPlayer;
                }
                selectedLayout();
                keepAwake();
                if (!deviceFacade.connected()){
                    deviceFacade.connect();
                    loadingView = findViewById(R.id.loading);
                    loadingView.setVisibility(View.VISIBLE);
                }
            }
        }else{
            findViewById(R.id.player_container_out).setVisibility(View.GONE);
            loadingView.setVisibility(View.GONE);
            connectView.setText(R.string.camera_offline);
            connectView.setVisibility(View.VISIBLE);
        }


    }


    protected boolean isMainPlayer() {
        return currentPlayer == PLAYER_ID_MAIN;
    }

    private void switchPlayer(int player, boolean cmd){
        if (currentPlayer == player) return;
        if (isSaving){
            MsgCenterToast.show(CameraPipLiveActivity.this, R.string.camera_player_screencap);
            return;
        }
        currentPlayer = player;
        if (mDeviceFeature != null){
            mDeviceFeature.currentPlayer = currentPlayer;
        }
        if (mDevice != null) {
            MultiPlayerHelper.writeChannel(this, mDevice.uuid, currentPlayer);
        }
        TGThreadPool.executeOnUiThread(this::selectedLayout);

        if (cmd) {
            AppHelper.setPrimaryViewCmd(deviceFacade, currentPlayer);
        }

        deviceFunHelper.setAudioImageResource(deviceMediaSource.isAudioProduceEnabled() ? R.drawable.ic_tange_live_soundon : R.drawable.ic_tange_live_soundoff);
        showBanner();
        setResolution();
        selectedLayout();
        putSettingsInfo();
    }

    void selectedLayout(){
        if (rendered){
            int pad = DimenUtil.dp2px(CameraPipLiveActivity.this, 2);
            if (isMainPlayer()) {
                playerContainer.setPadding(pad, pad, pad, pad);
                playerContainer.setBackgroundResource(R.drawable.player_view_pip_vertical_selected);
                playerContainerPiP.setBackgroundColor(Color.TRANSPARENT);
                playerContainerPiP.setPadding(0, 0, 0, 0);
            } else {
                playerContainer.setBackgroundColor(Color.TRANSPARENT);
                playerContainerPiP.setBackgroundResource(R.drawable.player_view_pip_vertical_selected);
                playerContainerPiP.setPadding(pad, pad, pad, pad);
                playerContainer.setPadding(0, 0, 0, 0);
            }
        }
    }

}
